const app = getApp();
const util = require('../../utils/util.js')
Page({
    data: {
        imgUrl: app.globalData.imgUrl,
        equipment:{},
        products:[],
        tracks:[],
        equipmentId:'',
        position:[],
        positionPicker:[],
        positionPickerIndex:'',
        files: [],
        filesId: [],
        enbleUpload: true,
        uploading: false,
        uploadFail: false,
        localFiles: [],
        enableUpload: true,
        isPercentSet: false,
        selectedArea:'请选择',
        equipmengName:''

    },
    onLoad: function (option) {
        wx.setNavigationBarTitle({
            title: '激活设备'
        })

        this.setData({
            imei:option.imei
        })
        this.getInactiveEquip(option.imei);
        this.getEquipmentPositon()


    },
    getInactiveEquip:function(imei){
        wx.showLoading({
            title: '加载中',
        });
        var that = this;
        wx.request({
            url: app.globalData.APIURL + '/vending-admin/active/getInactiveEquip',
            data: {
                token: app.globalData.token,
                imei: imei,
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                // 停止刷新
                wx.hideLoading();
                console.log(res.data)
                if (app.requestEro(res.data.success, res.data.msg)) {
                    that.setData({
                        equipment:res.data.equipment,
                        equipmentId:res.data.equipment.id,
                        products:res.data.products,
                        tracks:res.data.tracks
                    })
                    var param={};
                    for(var i=0;i<res.data.tracks.length;i++){
                        if(res.data.tracks[i].need_reload==0){
                            var product_id = "tracks["+ i +"].product_id";
                            param[product_id] = 1;
                        }
                    }

                    that.setData(param)

                }

            },
            fail: function (err) {
                console.log(err);
                wx.hideLoading();
            }
        })
    },
    getEquipmentInfoById: function (id) {
        var that = this;

        wx.request({
            url: app.globalData.APIURL + '/vending-admin/operator/getEquipDetail',
            data: {
                token: app.globalData.token,
                equipment_id: id,
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                console.log(res.data)
                if(app.requestEro(res.data.success,res.data.msg)){
                    that.setData({
                        equipmentTracks: res.data.equipmentTracks
                    })
                }
            },
            fail: function (err) {
                console.log(err)
            }
        })

    },


    adjustTrack: function (e) {
        console.log(e);
        wx.showLoading({
            title: '加载中',
        });
        var that = this;
        var trackType = e.currentTarget.id;
        var track = e.currentTarget.dataset.name;
        var id = this.data.equipmentId;
        wx.request({
            url: app.globalData.APIURL + '/vending-admin/active/getProductEachTrack',
            data: {
                token: app.globalData.token,
                cargo_type_id: trackType,
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                wx.hideLoading();
                console.log(res)
                if(app.requestEro(res.data.success,res.data.msg)){
                    var productName = [];
                    var productId = [];
                    res.data.cargoProducts.forEach(function (item, i) {
                        productName.push(item.productname);
                        productId.push(item.product_id);
                    });
                    wx.showActionSheet({
                        itemList: productName,
                        success: function (res) {
                            if (!res.cancel) {
                                console.log(res.tapIndex)
                                //修改货道商品显示
                                var index = res.tapIndex;
                                that.changeProduct(track,productId[index],productName[index])
                            }
                        }
                    });
                }

            },
            fail: function (err) {
                console.log(err)
            }
        })
    },

    changeProduct: function (track,productId,productName){
        var id = this.data.equipmentId;
        console.log(track,productId,productName);
        var param={};
        for(var i=0;i<this.data.tracks.length;i++){
            if(this.data.tracks[i].track==track){
                console.log(this.data.tracks[i])
                var product_name = "tracks["+ i +"].product_name";
                var product_id = "tracks["+ i +"].product_id";
                param[product_name] = productName;
                param[product_id] = productId;
            }
        }

        this.setData(param)
        console.log(param)
        console.log(this.data.tracks)

    },
    getEquipmentPositon: function () {
        var that = this;
        var id = this.data.equipmentId;
        wx.request({
            url: app.globalData.APIURL + '/vending-admin/active/getEquipPosition',
            data: {
                token: app.globalData.token,
                // cargo_type_id: trackType,
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                wx.hideLoading();
                console.log(res)
                if(app.requestEro(res.data.success,res.data.msg)){
                    that.setData({
                        position:res.data.positions
                    })
                    var positionName = [];
                    res.data.positions.forEach(function (item, i) {
                        positionName.push(item.value_desc);
                    });
                    that.setData({
                        positionPicker:positionName
                    })
                }

            },
            fail: function (err) {
                console.log(err)
            }
        })
    },
    selectPosition: function(e){
        console.log(e.detail.value)
        wx.showLoading({
            title:'加载中'
        })
        var that = this;
        var equipmentId = this.data.equipmentId;
        var position = this.data.position[e.detail.value].value;
        wx.request({
            url: app.globalData.APIURL + '/vending-admin/active/saveEquipPosition',
            data: {
                token: app.globalData.token,
                equipment_id:equipmentId,
                position: position,
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                wx.hideLoading();
                console.log(res)
                if(app.requestEro(res.data.success,res.data.msg)){
                    that.setData({
                        positionPickerIndex:e.detail.value,
                    })
                }

            },
            fail: function (err) {
                console.log(err)
            }
        })
    },
    setPrice: function (e){
        console.log(e)
        var price = e.detail.value;
        var listIndex = e.currentTarget.dataset.name;
        if(this.data.products[listIndex].price != price ){
            var that = this;
            var equipmentId = this.data.equipmentId;
            var productId = e.currentTarget.dataset.id;
            wx.request({
                url: app.globalData.APIURL + '/vending-admin/active/saveEquipProductPrice',
                data: {
                    token: app.globalData.token,
                    equipment_id:equipmentId,
                    product_id: productId,
                    price:price
                },
                // method:'GET',
                header: {
                    'content-type': 'application/json' // 默认值
                },
                success: function (res) {
                    wx.hideLoading();
                    console.log(res)
                    if(app.requestEro(res.data.success,res.data.msg)){

                    }

                },
                fail: function (err) {
                    console.log(err)
                }
            })
        }

    },
    chooseImage: function (e) {
        var that = this;
        wx.chooseImage({
            sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
            success: function (res) {
                // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
                that.setData({
                    localFiles: that.data.localFiles.concat(res.tempFilePaths),
                    uploading: true,
                    progress: 0,
                });

                const upload = wx.uploadFile({
                    // url: 'http://192.168.90.189:8080/vending-admin/active/uploadFile',
                    url: app.globalData.APIURL + '/vending-admin/active/uploadFile',
                    filePath: res.tempFilePaths[0],
                    name: 'file',
                    formData:{
                    },
                    success: function (res) {
                        var data = JSON.parse(res.data);
                        console.log(data);
                        if (data.success == 1) {
                            that.setData({
                                files: that.data.files.concat(that.data.localFiles[that.data.localFiles.length - 1]),
                                filesId: that.data.filesId.concat(data.fileId),
                                uploading: false,

                            });
                            that.setData({
                                enableUpload: that.data.files.length < 1 ? true : false,
                            })


                        } else {
                            var msg = data.msg;
                            wx.showModal({
                                content: msg,
                                showCancel: false,
                                success: function (res) {
                                    if (res.confirm) {
                                        console.log('用户点击确定')
                                    }
                                }
                            });
                        }
                        console.log(res);
                    },
                    fail: function (err) {
                        console.log(err);
                    }
                });
                upload.onProgressUpdate((res) => {
                    that.setData({
                        progress: res.progress
                    })

                })
            }
        })
    },

    previewImage: function (e) {
        wx.previewImage({
            current: e.currentTarget.id, // 当前显示图片的http链接
            urls: this.data.files // 需要预览的图片http链接列表
        })
    },

    activeEquipment: util.throttle(function () {
        wx.showLoading({
            title: '加载中',
        });
        var equipmentId= this.data.equipmentId;
        var pic = this.data.filesId[0];
        var param={equipmentTracks:this.data.tracks};
        console.log(equipmentId,pic,param,this.data.imei);
      console.log(JSON.stringify(param).length)
var that = this;
        wx.request({
            url: app.globalData.APIURL + '/vending-admin/active/active',
            // url: 'http://192.168.90.189:8080/vending-admin/active/active',
            data: {
                token: app.globalData.token,
                equipment_id: equipmentId,
                pic: pic,
                paras:JSON.stringify(param),
                imei:that.data.imei,
                name: that.data.equipmengName
            },
            // method:'GET',
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function (res) {
                console.log(res.data)
                wx.hideLoading();
                if(app.requestEro(res.data.success,res.data.msg)){
                    wx.showModal({
                        title: '激活成功',
                        showCancel: false,
                        success: function (res) {
                            if (res.confirm) {
                                wx.navigateBack({
                                    delta: 1
                                })
                            }
                        }
                    });
                }
            },
            fail: function (err) {
                console.log(err)
            }
        })
    }, 1000),
    bindNameInput:function (e) {
        console.log(e.detail.value);
        this.setData({
            equipmengName:e.detail.value
        })
    }


});